import { defineStore } from "pinia";
import api from "@/api";
import { showDialog } from "vant";

export const useAuthStore = defineStore("auth", {
  state: () => ({
    user: null, // 用户信息
    token: localStorage.getItem("token") || "", // 持久化 token
    lastLogin: null, // 最后登录时间
    isLoginDialogVisible: false,
    eventType: null,
    isrealLogin: false,//是否是真实的登录（区分不是游客静默登录）
    isLogin: true // 判断是显示登录还是显示注册
  }),
  // 正确配置持久化选项
  persist: {
    storage: localStorage,
    paths: ["token", "user", "isLoginDialogVisible", "eventType", "isrealLogin"], // 仅持久化指定字段
    key: "auth-store", // 自定义存储键名
  },
  actions: {
    // 显示登录弹窗方法
    showLoginDialog() {
      this.isLoginDialogVisible = true;
    },
    // 关闭登录弹窗方法
    hideLoginDialog() {
      this.isLoginDialogVisible = false;
    },
    // 登录逻辑
    async login(loginForm, router) {
      try {
        const response = await api.login(loginForm);
        // 更新状态
        this.user = response.data.name;
        this.token = response.data.token;
        this.eventType = response.data.eventType;
        this.lastLogin = new Date().toISOString();
        this.isrealLogin = true;//真实用户登录；
        // 持久化存储
        localStorage.setItem("token", response.data.token);
        // router.push("/");
        // 登录成功，刷新页面
        router.push("/").then(() => {
          window.location.reload(); // 在跳转完成后刷新
        });
        return true;
      } catch (error) {
        console.error("登录失败:", error);
        throw error;
      }
    },

    // 登出逻辑
    async logout() {
      try {
        await api.logout();
        // 更新状态
        this.user = null;
        this.token = "";
        localStorage.removeItem("token");
        localStorage.removeItem("auth-store");
        this.isrealLogin = false;
        showDialog({
          message: "Logged out",
          confirmButtonText: "OK",
          className: "custom-ok-dialog",
        }).then(() => {
          window.location.reload(); // 退出登录后，刷新页面
        });
      } catch (error) {
        console.error("登录失败:", error);
        throw error;
      }
    },
  },
  getters: {
    isAuthenticated: (state) => !!state.token,
    userInfo: (state) => state.user,
  },
});
